<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="客户名字" prop="khname">
        <el-input
          v-model="queryParams.khname"
          placeholder="请输入客户名字"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="地址" prop="dz">
        <el-input
          v-model="queryParams.dz"
          placeholder="请输入地址"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="wszt" :label-width="'100px'">
<!--        <el-select v-model="queryParams.wszt" style="width: 150px;" placeholder="请选择信息完善状态">-->
<!--          <el-option key="1" :label="'待完善'" value="1"></el-option>-->
<!--          <el-option key="2" :label="'已完善'" value="2"></el-option>-->
<!--        </el-select>-->
        <el-checkbox-group v-model="wszt" size="mini" @change="selectWszt">
          <el-checkbox border label="1">待完善</el-checkbox>
          <el-checkbox border label="2">已完善</el-checkbox>
        </el-checkbox-group>
      </el-form-item>
      <el-form-item label="创建日期">
        <el-date-picker
          style="width: 350px"
          v-model="querySj"
          @change="selectTime"
          value-format="yyyy-MM-dd HH:mm:ss"
          type="datetimerange"
          :default-time="['00:00:00', '23:59:59']"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期">
        </el-date-picker>
      </el-form-item>
      <el-row style="margin-bottom: 15px">
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-row>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['gd:khxx:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdateData"
          v-hasPermi="['gd:khxx:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="batchHandleDelete"
          v-hasPermi="['gd:khxx:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['gd:khxx:export']"
        >全部导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          plain
          icon="el-icon-download"
          size="mini"
          :disabled="multiple"
          @click="handleSelectExport"
          v-hasPermi="['gd:ywd:export']"
        >导出选择数据</el-button>
      </el-col>
      <el-col :span="1.5" v-if="this.$store.getters.name === 'admin'">
        <el-button
          type="success"
          plain
          size="mini"
          :disabled="multiple"
          @click="authData"
          v-hasPermi="['gd:ywd:export']"
        >授权选择数据</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="khxxList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"></el-table-column>
      <el-table-column label="编号" width="55" align="left" prop="bh" />
      <el-table-column label="客户名字" align="left" prop="khname">
        <template slot-scope="scope">
          <div style="color: #00afff;cursor: pointer;">
            <span @click="showInfo(scope.row)"> {{scope.row.khname}}</span> &nbsp;
            <el-link :underline="false" type="success" @click="copyText(scope.row.khname)" icon="el-icon-copy-document" style="font-size: 10px"></el-link>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="地址" align="left" prop="dz">
        <template slot-scope="scope">
          <div style="cursor: pointer;">
            <span> {{scope.row.dz}}</span> &nbsp;
            <el-link :underline="false" type="success" @click="copyText(scope.row.dz)" icon="el-icon-copy-document" style="font-size: 10px"></el-link>
          </div>
        </template>
      </el-table-column>
<!--      <el-table-column label="电话" width="110" align="left" prop="dh" />-->
      <el-table-column label="税号" align="left" prop="sh" width="140" >
        <template slot-scope="scope">
          <div style="cursor: pointer;">
            <span> {{scope.row.sh}}</span> &nbsp;
            <el-link :underline="false" type="success" @click="copyText(scope.row.sh)" icon="el-icon-copy-document" style="font-size: 10px"></el-link>
          </div>
        </template>
      </el-table-column>
<!--      <el-table-column label="银行卡号" align="center" prop="xhkh" />-->
      <el-table-column label="待完善" width="150" align="center" prop="wszt" >
        <template slot-scope="scope">
          <el-tag v-if="scope.row.wszt === '1'" type="warning">待完善</el-tag>
          <el-tag v-else type="success">已完善</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="排序" width="50" align="center" prop="px" />
      <el-table-column label="备注" width="150" align="center" prop="bz" show-overflow-tooltip />
      <el-table-column label="录入人" width="70" align="left" prop="createBy" />
      <el-table-column label="录入时间" width="150" align="center" prop="createTime" />
      <el-table-column label="操作" width="120" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
<!--          v-if="updateDelAuth(scope.row.status)"-->
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['gd:khxx:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['gd:khxx:remove']"
          >删除</el-button>
          <el-button
            v-if="scope.row.delFlag === '1'"
            size="mini"
            type="text"
            icon="el-icon-refresh-right"
            v-hasPermi="['gd:khxx:remove']"
            @click="recover(scope.row)"
          >恢复数据</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改客户信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" @close="cancel" width="70%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="客户名字" prop="khname">
              <el-input v-model="form.khname" placeholder="请输入客户名字" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="地址" prop="dz">
              <el-input v-model="form.dz" placeholder="请输入地址" />
            </el-form-item>
          </el-col>
        </el-row>
       <el-row>
         <el-col :span="12">
           <el-form-item label="税号" prop="sh">
             <el-input v-model="form.sh" placeholder="请输入税号" />
           </el-form-item>
         </el-col>
         <el-col :span="12">
           <el-form-item label="银行卡号" prop="xhkh">
             <el-input v-model="form.xhkh" placeholder="请输入银行卡号" />
           </el-form-item>
         </el-col>
       </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="电话" prop="dh">
              <el-input v-model="form.dh" type="number" placeholder="请输入电话" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="排序" prop="px">
              <el-input v-model="form.px" type="number" placeholder="请输入排序" />
            </el-form-item>
          </el-col>
        </el-row>
       <el-row>
         <el-col :span="12">
           <el-form-item label="录入人" prop="createBy">
             <el-input v-model="form.createBy" readonly />
           </el-form-item>
         </el-col>
         <el-col :span="12">
           <el-form-item label="录入时间" prop="createTime">
             <el-input v-model="form.createTime" readonly />
           </el-form-item>
         </el-col>
       </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="bz">
              <el-input
                type="textarea"
                maxlength="1000"
                :autosize="{ minRows: 3, maxRows: 4 }"
                show-word-limit
                placeholder="请输入内容"
                v-model="form.bz">
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button v-if="ShowBtn" :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listKhxx, getKhxx, delKhxx, addKhxx, updateKhxx, authDatas, recoverData, getMaxBh } from '@/api/gd/khxx'

export default {
  name: "Khxx",
  data() {
    return {
      querySj: [],
      userName: this.$store.getters.name,
      ShowBtn: true,
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 客户信息表格数据
      khxxList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      wszt: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        khname: undefined,
        dz: undefined,
        sh: undefined,
        xhkh: undefined,
        px: undefined,
        bz: undefined,
        createBy: this.$store.getters.name,
        params: {
          startTime: '',
          endTime: ''
        }
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        khname: [
          { required: true, message: "客户名字不能为空", trigger: "blur" }
        ],
        dz: [
          { required: true, message: "地址不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    selectWszt(val) {
      this.queryParams.wszt = val.toString()
      this.getList()
    },
    selectTime(time) {
      this.queryParams.params.startTime = time[0]
      this.queryParams.params.endTime = time[1]
    },
    updateDelAuth(status) {
      return this.userName === 'admin' || status === '1'
    },
    copyText(data) {
      const textarea = document.createElement('textarea');
      textarea.value = data;
      document.body.appendChild(textarea);
      textarea.select();
      try {
        // 尝试执行复制操作
        const success = document.execCommand('copy');
        if (success) {
          this.$message.success("已复制！")
        } else {
          this.$message.error("复制失败！")
        }
      } catch (error) {
        this.$message.error("复制失败！")
      }
      document.body.removeChild(textarea);
    },
    showInfo(row) {
      this.form = row
      this.open = true
      this.ShowBtn = false
      this.title = "客户信息";
    },
    /** 查询客户信息列表 */
    getList() {
      this.loading = true;
      listKhxx(this.queryParams).then(response => {
        this.khxxList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.ShowBtn = true
      this.reset();
      this.getList()
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        khname: undefined,
        dz: undefined,
        sh: undefined,
        xhkh: undefined,
        px: undefined,
        bz: undefined,
        createBy: this.$store.getters.nickName,
        createTime: '',
        updateBy: undefined,
        updateTime: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        khname: undefined,
        dz: undefined,
        sh: undefined,
        xhkh: undefined,
        px: undefined,
        bz: undefined,
        createBy: this.$store.getters.name,
        params: {
          startTime: '',
          endTime: ''
        }
      }
      this.querySj = []
      this.wszt = []
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    async handleAdd() {
      this.reset();
      // 新增的时候添加用户默认排序
      let bh = await getMaxBh()
      this.$set(this.form, 'px', bh)
      this.open = true;
      this.title = "添加客户信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.loading = true;
      this.reset();
      // 判断当前的数据是否有权限修改
      const id = row.id || this.ids
      getKhxx(id).then(response => {
        this.loading = false;
        this.form = response.data;
        this.open = true;
        this.title = "修改客户信息";
      });
    },
    handleUpdateData() {
      let ids = this.ids
      // const obj = this.khxxList.filter(item => ids.some(id => id === item.id))[0]
      // if (obj !== null && obj !== undefined && obj.status === '0' && this.userName !== 'admin') {
      //   this.$message.error("您无权限修改 " + obj.khname + " 客户信息")
      // }else {
      //   getKhxx(ids).then(response => {
      //     this.loading = false;
      //     this.form = response.data;
      //     this.open = true;
      //     this.title = "修改客户信息";
      //   });
      // }
      getKhxx(ids).then(response => {
        this.loading = false;
        this.form = response.data;
        this.open = true;
        this.title = "修改客户信息";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.buttonLoading = true;
          this.form.status = '0'  // 新增，或者修改，则将状态改为0
          if (this.form.id != null) {
            updateKhxx(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          } else {
            addKhxx(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    batchHandleDelete() {
      const ids = this.ids;
      const obj = this.khxxList.filter(item => ids.some(id => id === item.id))
      // 查询当前不可以删除的数据
      // let delData = obj.filter(item => item.status === '0')
      // if (delData.length > 0 && this.userName !== 'admin') {
      //   let dataNames = delData.map(item => item.khname)
      //   this.$message.error("您无权限删除 " + dataNames + " 客户信息")
      // }else {
      //   // 获取当前客户的姓名
      //   const data = obj.map(item => item.khname)
      //   this.$modal.confirm('请确认是否删除 ' + data + ' 客户').then(() => {
      //     this.loading = true;
      //     return delKhxx(ids);
      //   }).then(() => {
      //     this.loading = false;
      //     this.getList();
      //     this.$modal.msgSuccess("删除成功");
      //   }).catch(() => {
      //   }).finally(() => {
      //     this.loading = false;
      //   });
      // }
      const data = obj.map(item => item.khname)
      this.$modal.confirm('请确认是否删除 ' + data + ' 客户').then(() => {
        this.loading = true;
        return delKhxx(ids);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      }).finally(() => {
        this.loading = false;
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id
      this.$modal.confirm('请确认是否删除 ' + row.khname + ' 客户').then(() => {
        this.loading = true;
        return delKhxx(ids);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      }).finally(() => {
        this.loading = false;
      });
    },
    /** 恢复按钮操作 */
    recover(row) {
      const ids = row.id
      this.$modal.confirm('请确认是否恢复 ' + row.khname + ' 客户数据').then(() => {
        this.loading = true;
        return recoverData(ids);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      }).finally(() => {
        this.loading = false;
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      let name = this.getTodayDate()
      this.download('gd/khxx/export', {
        ...this.queryParams
      }, `${name} 客户信息_${new Date().getTime()}.xlsx`)
    },
    handleSelectExport() {
      const ids = this.ids;
      let name = this.getTodayDate()
      this.download('gd/khxx/exportSelectDat/' + ids, {
        ...this.queryParams
      }, `${name} 客户信息_${new Date().getTime()}.xlsx`)
    },
    getTodayDate() {
      const date = new Date();
      const year = date.getFullYear();
      const month = ('0' + (date.getMonth() + 1)).slice(-2);
      const day = ('0' + date.getDate()).slice(-2);
      return `${year}${month}${day}`;
    },
    authData() {
      const ids = this.ids;
      const data = this.khxxList.filter(item => ids.some(id => id === item.id)).map(item => item.khname)
      this.$modal.confirm('请确认是否要给 ' + data+' 客户授权').then(() => {
        this.loading = true;
        return authDatas(ids);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.$modal.msgSuccess("授权成功！");
      }).catch(() => {
      }).finally(() => {
        this.loading = false;
      });
    }
  }
};
</script>
<style>
/*调换两个按钮的位置*/
.el-message-box__btns{
  display:flex;
  flex-direction:row-reverse;
}

/*拉开两个按钮的距离10像素，给取消按钮10像素的左margin。*/
.custom-cancel-button{
  margin-left:10px;
}
</style>

